from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

# 碳效算法嵌入的导入

# 缓存用于暂时存储数据
from django.core.cache import cache
from django.views.decorators.csrf import csrf_exempt

from index.api_ops import *
from index.basic_db_ops import *
from index.basic_db_ops2 import *
from index.models import *
from .cheat import get_cheat
from .db_Session import get_db_session


# 碳效算法嵌入的导入
# 导入光伏读写函数
# from index.client_get_or_input_data import input_data


# engine = create_engine(f'postgresql://{user_name}:{password}@localhost:5432/{db_name}', echo=True)
# engine = create_engine(f'postgresql://{user_name}:{password}@localhost:5432/{db_name}', echo=False)
# Session = sessionmaker(bind=engine)  # 生成 Session 类，在这个数据库操作之中，只需要Session类就可以，实例化的对象在各个函数当中
# print(f"已经成功连接到本地的数据库{db_name}")


# 写入基站数据
def write_bs_data():
    """主函数，每秒写入一次基站数据"""
    bs_id = 1  # 初始基站编号
    for _ in range(5):
        # 调用写入函数
        # 秒级数据
        # write_second_bs_data(Session,bs_id)
        # 分钟级数据
        # write_bs_minute_data(Session,bs_id)
        # 小时级数据
        write_bs_hourly_data(Session, bs_id)
        # 每60秒执行一次
        time.sleep(2)



@csrf_exempt
def api_bs_info(request):
    try:
        Session = get_db_session()
        pos, number = pos_bs_element(Session)

        # 生成返回的内容
        bs_info = dict()
        if cache.get("bs_num") is not None:
            bs_info["number"] = cache.get("bs_num")
        else:
            bs_info["number"] = get_bs_virtual_scene(Session, 1, "bs_number")
            bs_info["number"] = number

        bs_info["position"] = pos

        print(f"成功返回json格式的基站固定信息数据")
        return JsonResponse(bs_info)
    except Exception as e:
        print(f"获取基站固定信息时出现错误: {e}")
        return JsonResponse({"错误": "获取基站固定信息时出现错误:" + str(e)}, status=500)


@csrf_exempt
def api_user_info(request):
    try:
        Session = get_db_session()

        # request_data = json.loads(request.body)
        request_data = json.loads(request.body)
        time_id = request_data.get("time")

        # pos, number = pos_user_element(Session, time_id)
        user_number = count_scene_user_element(Session, time_id)
        # 生成返回的内容
        user_info = dict()
        user_info["time"] = time_id
        user_info["number"] = user_number
        data = []

        # 提取出SNR
        user_snr = cache.get(f"SNR{time_id}").tolist()

        # 提取出信道状态
        channel_status = cache.get(f"CHANEL{time_id}").tolist()

        # userrank:1-user_number
        for userrank in range(1, user_number + 1, 1):
            single_data = dict()
            single_data["position"] = {"X": round_num(get_scene_user_element(Session, "lon", time_id, userrank)),
                                       "Y": round_num(get_scene_user_element(Session, "lat", time_id, userrank))}
            single_data["user_snr"] = user_snr[userrank - 1]
            single_data["status"] = round_list_or_matrix(channel_status[userrank - 1])
            data.append(single_data)

        user_info["data"] = data
        print(f"成功返回json格式的用户固定信息数据")
        return JsonResponse(user_info)
    except Exception as e:
        print(f"获取用户固定信息时出现错误: {e}")
        return JsonResponse({"错误": str(e)}, status=500)


@csrf_exempt
def api_final_res(request):
    if request.method == 'POST':
        try:
            # 嵌入最终的优化算法，返回三种优化情况的结果：1.用户关联且基站休眠的最优结果 2.用户关联但是基站不休眠优化结果  3.就近接入（用户不关联）基站休眠优化结果
            # 仿真的结果根据仿真场景的时间而定，所以实现进行获取time_id
            # 以下为数据的规范命名名称
            # bs_num, ue_num, bs_pos, ue_pos, p_pv, rb_req, l_bs_ue, h_bs_ue

            Session = get_db_session()

            # seed_num = 1
            # const.modify_const("SEED", seed_num)
            # np.random.seed(const.SEED)

            request_data = json.loads(request.body)
            time_id = request_data.get("time")
            if cache.get("bs_num") is not None:
                bs_num = cache.get("bs_num")
            else:
                bs_num = const

            # ue_num = cache.get(f"ue_num")
            # if cache.get("ue_num") is not None:
            #     cache.get("ue_num")
            # else
            ue_num = count_scene_user_element(Session, time_id)
            # 读取基站以及用户位置
            bs_pos = cache.get(f"bs_pos")
            # else:
            #     bs_pos = uniform2d(bs_num - 1, const.L)
            #     bs_pos = macro_bs_init(bs_pos, const.L)

            # if cache.get(f"user_pos{time_id}"):
            ue_pos = cache.get(f"user_pos{time_id}")
            # ue_pos = np.array(ue_pos)

            # 读取用户要求和信道状态
            ue_snr_theta = cache.get(f"SNR{time_id}")
            h_bs_ue = cache.get(f"CHANEL{time_id}")

            # 得到当前时刻的光伏能量
            e_pv = cache.get(f"e_pv{time_id}")

            l_bs_ue = distance_calculation(bs_pos, ue_pos)  # 测算距离
            _, rb_req = rb_demand(ue_snr_theta, l_bs_ue, h_bs_ue)

            result_optimal, result_unsleep, result_without_association \
                = userassociation_energysharing_once(bs_num, ue_num, bs_pos, ue_pos, e_pv, rb_req, l_bs_ue, h_bs_ue)

            # 目前返回用户关联基站休眠的最终结果
            # print(result_optimal)
            # print(result_unsleep)
            # print(result_without_association_optimal)

            # 获取三种优化情况的最终结果，其类型是Onetimeresult
            bs_ue_optimal = result_optimal.x_bs_ue
            bs_ue_unsleep = result_unsleep.x_bs_ue
            bs_ue_withoutassociation = result_without_association.x_bs_ue
            # 更新用户的归属的基站，对于每一个最后的优化结果进行遍历
            # 需要注意，在这里基站的序号从0开始

            # 记录基站的归属用户个数，只有用户关联且基站休眠的最优结果需要进行记录，用于更新数据库
            belong_list = [0 for _ in range(bs_num)]
            # belong_bs_ue_unsleep_list = [0 for _ in range(bs_num)]
            # belong_bs_ue_withoutassociation = [0 for _ in range(bs_num)]

            # 记录用户归属的基站序号，三种情况都需要进行记录，如[2, 3, 4, 2, 1]
            belong_bs_ue_optimal = []
            belong_bs_ue_unsleep = []
            belong_bs_ue_withoutassociation = []

            for i in range(ue_num):
                # 首先处理用户关联且基站休眠的优化结果
                # 这里的基站的序号是从1开始的
                # 获取所属的基站序号，查找1即查找当前未休眠的基站，因为是在关联的列表当中，所以此时的idx从0开始
                idx = bs_ue_optimal[i].tolist().index(1)
                # 更新基站连接用户数量
                belong_list[idx] += 1
                # 当前用户在基站下的位次
                cur_belong = belong_list[idx]
                # 记录用户所属的基站
                idx += 1
                belong_bs_ue_optimal.append(idx)
                print(f"在用户关联且基站休眠情况下，用户{i + 1}所属的基站是{idx}")
                # 写入当前用户的数据库，指明所属基站以及属于基站的第几个用户
                update_scene_user_element(Session, "bs_identifier", idx, time_id, time_userrank=i + 1)
                update_scene_user_element(Session, "user_id_scene", cur_belong, time_id, time_userrank=i + 1)

                # 用户关联但是基站不休眠优化结果的情况
                idx2 = bs_ue_withoutassociation[i].tolist().index(1)
                idx2 += 1
                belong_bs_ue_unsleep.append(idx2)

                # 就近接入（用户不关联）基站休眠优化结果
                idx3 = bs_ue_unsleep[i].tolist().index(1)
                idx3 += 1
                belong_bs_ue_withoutassociation.append(idx3)

            """
            对于用户关联且基站休眠的优化结果，传回最后要进行发送的优化的数据：
            :param time_id: 时间
            :param bs_status: 基站信息
            :param res_x_ue: 用户关联策略
            :param ce: 碳效
            :param rate: 用户速率
            :param bs_consumption: 基站功耗
            :param bs_CO2: 基站碳排放
            :param data_volume: 总数据量
            """
            # 总的返回结果
            res_return = dict()

            # 用户关联且基站休眠的优化结果 result_optimal
            res_op = dict()
            res_op["time_id"] = time_id
            res_op["bs_status"] = result_optimal.bs_status.tolist()[0]
            res_op["res_x_ue"] = belong_bs_ue_optimal
            res_op["ce"] = round_num(result_optimal.ce)
            res_op["rate"] = round_list_or_matrix(result_optimal.r_ue.tolist())
            res_op["bs_consumption"] = round_list_or_matrix(result_optimal.p_bs.tolist()[0])
            res_op["bs_CO2"] = round_list_or_matrix(result_optimal.E_carbon.tolist()[0])
            res_op["data_volume"] = round_num(result_optimal.B)
            res_op["consume_pv"] = round_num(result_optimal.consume_pv)
            res_op["city_e"] = round_num(result_optimal.city_e)
            res_op["pv_rate"] = round_num(result_optimal.pv_rate)
            res_return["result_optimal"] = res_op

            # 用户关联但是基站不休眠优化结果 result_unsleep
            res_unsleep = dict()
            res_unsleep["time_id"] = time_id
            res_unsleep["bs_status"] = result_unsleep.bs_status.tolist()[0]
            res_unsleep["res_x_ue"] = belong_bs_ue_unsleep
            res_unsleep["ce"] = round_num(result_unsleep.ce)
            res_unsleep["rate"] = round_list_or_matrix(result_unsleep.r_ue.tolist())
            res_unsleep["bs_consumption"] = round_list_or_matrix(result_unsleep.p_bs.tolist()[0])
            res_unsleep["bs_CO2"] = round_list_or_matrix(result_unsleep.E_carbon.tolist()[0])
            res_unsleep["data_volume"] = round_num(result_unsleep.B)
            res_unsleep["consume_pv"] = round_num(result_unsleep.consume_pv)
            res_unsleep["city_e"] = round_num(result_unsleep.city_e)
            res_unsleep["pv_rate"] = round_num(result_unsleep.pv_rate)
            res_return["result_unsleep"] = res_unsleep

            # 就近接入（用户不关联）基站休眠优化结果 result_without_association
            res_without_association = dict()
            res_without_association["time_id"] = time_id
            res_without_association["bs_status"] = result_without_association.bs_status.tolist()[0]
            res_without_association["res_x_ue"] = belong_bs_ue_withoutassociation
            res_without_association["ce"] = round_num(result_without_association.ce)
            res_without_association["rate"] = round_list_or_matrix(result_without_association.r_ue.tolist())
            res_without_association["bs_consumption"] = round_list_or_matrix(result_without_association.p_bs.tolist()[0])
            res_without_association["bs_CO2"] = round_list_or_matrix(result_without_association.E_carbon.tolist()[0])
            res_without_association["data_volume"] = round_num(result_without_association.B)
            res_without_association["consume_pv"] = round_num(result_without_association.consume_pv)
            res_without_association["city_e"] = round_num(result_without_association.city_e)
            res_without_association["pv_rate"] = round_num(result_without_association.pv_rate)
            res_return["result_without_association"] = res_without_association

            # cache.set("res_return", res_return, 15 * 60)
            # 返回最终的数据
            return JsonResponse(res_return, status=200)

        except json.JSONDecodeError:
            return JsonResponse({'error': 'Invalid JSON format'}, status=400)
        except Exception as e:
            # if str(e) == "NoneType' object has no attribute 'shape":
            #     res_return = cache.get("res_return")
            #     return JsonResponse(res_return, status=200)
            return JsonResponse({'error': str(e)}, status=500)
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=405)


@csrf_exempt
def single_bs(request):
    if request.method == 'POST':
        try:
            Session = get_db_session()
            data = json.loads(request.body)
            """
            输入的样式案例
                "index": 1,
                "power": 200,
                "bandwidth": "50M",
                "start": 1742137978.0, // 2025 - 03 - 16 23:12:58
                "end": 1742054532, // 2025 - 03 - 16 00: 02:12
                "status": false
            """

            print("现在的data是:")
            print(data)
            bs_id = data.get("baseStationNumber")

            # # 如果基站的序号＞最大的基站序号，那么无法进行更新
            # if bs_id > get_bs_virtual_scene(Session, 1, "bs_number") or bs_id < 1:
            #     return JsonResponse({"错误": "修改基站序号超过当前可供设置的基站数量"}, status=400)

            power_rf = data.get("transmissionPower")
            bandwidth = data.get("bandwidth")
            start_time = data.get("startTime")
            end_time = data.get("endTime")
            status_rf = data.get("antennaStatus")

            # 起始与终止时间实际上传的就是字符串
            # tm_format = "%H:%M:%S"
            # start_time_str = start.strftime(tm_format)
            # end_time_str = end.strftime(tm_format)
            start_time_str = start_time
            end_time_str = end_time

            if isinstance(bandwidth, str):
                integer_bandwidth = int(re.sub(r'\D', '', bandwidth))
            elif isinstance(bandwidth, int):
                integer_bandwidth = bandwidth
            else:
                print("输入的bandwidth格式错误")
                integer_bandwidth = 100

            # 逐一进行更新
            update_bs_virtual_scene(Session, bs_id, "transmit_power", power_rf)
            update_bs_virtual_scene(Session, bs_id, "bandwidth", integer_bandwidth)
            update_bs_virtual_scene(Session, bs_id, "sleep_period", start_time_str + "-" + end_time_str)
            update_bs_virtual_scene(Session, bs_id, "rf_status", status_rf)

            # return HttpResponse(f"当前的基站{bs_id}更新完毕")
            return JsonResponse({"message": f"当前的基站{bs_id}更新完毕"}, status=200)
        except Exception as e:
            print(f"当前的错误是{str(e)}")
            return JsonResponse({'error': str(e)}, status=500)
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=405)


@csrf_exempt
def multiple_bs(request):
    try:
        Session = get_db_session()
        data = json.loads(request.body)
        print("现在的data是:")
        print(data)

        # 获取更新单一基站的全部参数
        start_bs_id = data.get("startIndex")
        end_bs_id = data.get("endIndex")
        power_rf = data.get("power")
        bandwidth = data.get("bandwidth")
        start_time = data.get("start")
        end_time = data.get("end")
        status_rf = data.get("status")

        # 时间戳转化为时间
        # start = datetime.fromtimestamp(start_time)
        # end = datetime.fromtimestamp(end_time)
        # tm_format = "%H:%M:%S"
        # 实际上直接是时间的字符串
        start_time_str = start_time
        end_time_str = end_time

        if isinstance(bandwidth, str):
            integer_bandwidth = int(re.sub(r'\D', '', bandwidth))
        elif isinstance(bandwidth, int):
            integer_bandwidth = bandwidth
        else:
            print("输入的bandwidth格式错误")
            integer_bandwidth = 100

        # 逐一进行更新
        for bs_id in range(start_bs_id, end_bs_id + 1):
            update_bs_virtual_scene(Session, bs_id, "transmit_power", power_rf)
            update_bs_virtual_scene(Session, bs_id, "bandwidth", integer_bandwidth)
            update_bs_virtual_scene(Session, bs_id, "sleep_period", start_time_str + "-" + end_time_str)
            update_bs_virtual_scene(Session, bs_id, "rf_status", status_rf)

        return JsonResponse({"message": f"复数个基站{start_bs_id}到{end_bs_id}更新完毕"}, status=200)
    except Exception as e:
        print(f"当前的错误是{str(e)}")
        return JsonResponse({'error': str(e)}, status=400)


@csrf_exempt
def set_para(request):
    """
    直接初始化仿真场景，直接生成基站以及用户
    相当于原本virtual_scene当中的两个功能
    :param request:
    :return:
    """
    try:
        Session = get_db_session()
        request_data = json.loads(request.body)
        '''
        请求样例
        "number": 4,
        "bs_location": "uniform2d",
        "users": "uniform2d",
        "interface": "ccp",
        "algorithm": "convex"
        }
        '''
        bs_num = request_data.get("number")
        bs_location_alg = request_data.get("bs_location")
        user_location_alg = request_data.get("users")
        interface = request_data.get("interface")
        optimize_alg = request_data.get("algorithm")
        trad_factor = request_data.get("trad_factor")  # 传统能源的碳排放因子
        pv_factor = request_data.get("pv_factor")  # 光伏能源的碳排放因子

        cache.set("current_parameter", request_data, 15*60)
        if trad_factor is None:
            trad_factor = 8
        if pv_factor is None:
            pv_factor = 1
        factor_unit = 1e-4
        if (not 1 <= trad_factor < 10) or (not 1 <= pv_factor < 10):
            trad_factor = 8
            pv_factor = 1
            print("输入的范围不对")
        trad_factor = trad_factor * factor_unit
        pv_factor = pv_factor * factor_unit
        # 设置模块常量
        const.modify_const("ETA_GRID", trad_factor)
        const.modify_const("ETA_PV", pv_factor)

        # bs_num可以直接写入cache当中，便于直接进行读取
        cache.set("bs_num", bs_num, 15 * 60)

        # 在参数设置阶段，对于模块常量当中bs_num影响算法的参数进行设置
        const.modify_const("BS_NUM", bs_num)
        const.modify_const("RB_MAX", get_RB_MAX(bs_num))
        const.modify_const("RB_W", get_RB_W(bs_num))
        const.modify_const("P_WORK", get_P_WORK(bs_num))
        const.modify_const("P_SLEEP", get_P_SLEEP(bs_num))
        const.modify_const("ONE_BS", get_ONE_BS(bs_num))
        const.modify_const("ZERO_BS", get_ZERO_BS(bs_num))
        # =========================================================================
        # 在进行虚拟场景的生成需要：1.获取新的场景的基本信息 2.删除原本的场景 3.初始化新的场景(2,3实际操作上是一步)
        # 4.根据获取的参数对于场景信息更新，包含1当中的基本信息的更新
        # 先确定生成的算法
        # 有uniform2d, ppp2d两种
        summon_alg = {"uniform2d": uniform2d, "ppp2d": ppp2d}

        # # 1.获取新的场景的基本信息：确定生成的算法
        # # 基站位置生成算法
        # # 此时需要对于基站进行生成，主要表现为得到经纬度
        if bs_location_alg in summon_alg.keys():
            bs_summon = summon_alg[bs_location_alg]
            bs_summon = uniform2d
        else:
            bs_summon = uniform2d
            bs_location_alg = "uniform2d"
            print("当前的基站生成算法无效，设定为uniform2d")


        # 对于所有基站进行生成算法的更新
        update_all_bs_virtual_scene(Session, bs_num, 'bs_location_generation_algorithm', bs_location_alg)
        print("成功更新基站生成算法:", bs_location_alg)

        # 用户位置生成算法
        # 此时需要对于基站进行生成，主要表现为得到经纬度
        if user_location_alg in summon_alg.keys():
            user_summon = summon_alg[user_location_alg]
            user_summon = uniform2d
        else:
            user_summon = uniform2d
            user_location_alg = "uniform2d"
            print("当前的用户生成算法无效，设定为uniform2d")

        update_all_bs_virtual_scene(Session, bs_num, 'user_location_generation_algorithm', user_location_alg)
        print("成功更新用户生成算法:", user_location_alg)
        print("成功更新用户接入方式:", interface)
        print("成功更新优化算法:", optimize_alg)

        # =========================================================================
        # 初始化基站
        # 基于数据表关联关系，先删除基站，后删除用户
        delete_all_scene_bs_element(Session)
        delete_all_scene_user_element(Session)

        # 在删除之后进行初始化
        # 场景信息初始化
        write_bs_virtual_scene(Session, bs_num)
        print("成功进行场景信息的初始化")
        # 基站状态初始化
        initialize_bs_element(Session, bs_num)
        print("成功进行基站状态的初始化")

        # 如果有缓存则，比较是不是一样，如果不一样那么就更新
        if cache.get("bs_location_generation_algorithm") is not None:
            bs_location_alg = cache.get("bs_location_generation_algorithm")
        if cache.get("user_location_generation_algorithm") is not None:
            user_location_alg = cache.get("bs_location_generation_algorithm")
        update_all_bs_virtual_scene(Session, bs_num, 'bs_location_generation_algorithm', bs_location_alg)
        update_all_bs_virtual_scene(Session, bs_num, 'user_location_generation_algorithm', user_location_alg)

        cache.set("bs_location_generation_algorithm", bs_location_alg, 15*60)
        cache.set("user_location_generation_algorithm", user_location_alg, 15*60)

        bs_pos = bs_summon(bs_num - 1, const.L)
        bs_pos = macro_bs_init(bs_pos, const.L)  # 最终的bs位置
        cache.set("bs_pos", bs_pos, 15 * 60)

        # 对于每一个基站都更新位置信息，位置信息随机生成
        for bs_id in range(1, bs_num + 1):
            lon = bs_pos[bs_id - 1][0]
            lat = bs_pos[bs_id - 1][1]
            update_scene_bs_element(Session, "lon", lon, bs_id)
            update_scene_bs_element(Session, "lat", lat, bs_id)
        print("成功进行基站位置的初始化")
        # =========================================================================
        # 初始化用户，即删除所有的数据
        delete_all_scene_user_element(Session)

        # 用户数量暂时使用预设数量
        # 时间影响因素，用户的数量
        # time_id = 0
        for time_id in range(0, 24, 1):
            user_number = const.UE_NUM_SEQUENCE[time_id]
            print(f"在{time_id}时刻的用户数量是{user_number}")

            # 获取基站数量, 缓存里有就用缓存的，要么就直接从数据库里提取
            # if cache.get("bs_num"):
            #     bs_number = cache.get("bs_num")
            # else:
            #     bs_number = get_bs_virtual_scene(Session, 1, "bs_number")

            # 生成SNR数据，暂时存放在cache中，时长15min，key为”SNR+数字“，如SNR0
            user_snr_theta = np.random.randint(const.SINR_MIN, const.SINR_MAX, size=[user_number, 1])
            cache.set(f"SNR{time_id}", user_snr_theta, 15 * 60)
            print("成功进行用户信噪比SNR的初始化")

            # 生成CHANEL数据，暂时存放在cache中，时长15min，key为"CHANEL+数字“，如CHANEL0
            user_channel_status = channel_status(bs_num, user_number)
            cache.set(f"CHANEL{time_id}", user_channel_status, 15 * 60)
            print("成功进行用户信道状态channel_status的初始化")

            # 用户信息初始化
            initialize_scene_user_element(Session, user_number, time_id, delete_option=False)

            # 生成用户的位置
            user_pos = user_summon(user_number, const.L)
            for user_rank in range(1, user_number + 1):
                lon = user_pos[user_rank - 1][0]
                lat = user_pos[user_rank - 1][1]
                update_scene_user_element(Session, "lon", lon, time_id, user_rank)
                update_scene_user_element(Session, "lat", lat, time_id, user_rank)

            # 全部用户位置信息，暂时存放在cache中，时长15min
            cache.set(f"user_pos{time_id}", user_pos, 15 * 60)
            print(f"在时刻{time_id}成功进行用户位置的初始化")

        # =========================================================================
        # 初始化光伏能量
        # 生成记录光伏能量的矩阵，其中行为时间，列为能量
        day_pv = np.zeros((24, const.BS_NUM))  # shape [24, const.BS_NUM]

        # 生成光伏功率
        p_pv = np.random.poisson(const.PV_A, [1, const.BS_NUM])

        # 光伏板面积，宏基站以及微基站处的面积不同，S_PV_MACRO以及S_PV_MICRO
        s_pv = [const.S_PV_MICRO for _ in range(const.BS_NUM - 1)]
        s_pv.insert(0, const.S_PV_MACRO)

        # 最终的光伏能量
        p_pv = p_pv * s_pv * const.GAMMA_PV  # shape = [1, bs_num]

        # 遍历每一个基站
        for bs_index in range(const.BS_NUM):
            # 遍历一天中的每一个小时（共 24 小时）
            for time_id in range(0, 24):
                # 利用指数函数计算当前基站在当前时刻的光伏功率
                # np.exp(-(time_id - const.PV_B) ** 2 / const.PV_C ** 2) 是指数衰减项，模拟光伏功率随时间变化
                day_pv[time_id, bs_index] = p_pv[0, bs_index] * np.exp(
                    -(time_id - const.PV_B) ** 2 / const.PV_C ** 2)
        for time_id in range(0, 24):
            e_pv = np.array([day_pv[time_id, :]])
            # 生成e_pv数据，为实际上的某一个时间的光伏能量，暂时存放在cache中，时长15min，key为”e_pv+数字“，如e_pv2
            cache.set(f"e_pv{time_id}", e_pv, 15 * 60)

        # return HttpResponse("虚拟场景的初始化已经完成")
        return JsonResponse({"message": "虚拟场景的初始化已经完成"}, status=200)
    except Exception as e:
        print(f"当前的错误是{str(e)}")
        return JsonResponse({'error': str(e)}, status=400)


@csrf_exempt
def real_station(request):
    try:
        """
         {'bandWidth':"100M"},//带宽
         {'power': 22}
         {'start': 1745039413000, 'end': 1745043017000}
         {'state': False}: false//射频状态
         {'switch': False} false//供电开关
         以上的情况随机来一个
        """
        Session = get_db_session()
        request_data = json.loads(request.body)

        print("这里是real_station，请求体的数据是：\n", request_data)
        # 获取请求里所有的数据
        # if request_data.get("bandWidth") is not None:
        #     print("处理的是bandWidth")
        #     bandwidth = request_data.get("bandWidth")
        #     # bandwidth的修改
        #     if bandwidth == "60M" or bandwidth == '80':
        #         set_60m()
        #     elif bandwidth == "100M" or bandwidth == '100':
        #         set_100m()
        #     elif bandwidth == "20M" or bandwidth == "20":
        #         set_20m()
        #     elif bandwidth == "30M" or bandwidth == "30":
        #         set_30m()
        #     elif bandwidth == "40M" or bandwidth == "40":
        #         set_40m()
        #     elif bandwidth == "80M" or bandwidth == "80":
        #         set_80m()
        #     else:
        #         pass
        #
        # elif request_data.get("power") is not None:
        #     transmission_power = request_data.get("power")
        #     action("set_MaxTxPower_info", transmission_power)
        # if request_data.get("start"):
        #     # start_time = start
        #     return JsonResponse({"message": "真实基站的数据已经修改"}, status=200)
        # if request_data.get("end"):
        #     return JsonResponse({"message": "真实基站的数据已经修改"}, status=200)
        # # start_time = sleep_time["start"]
        # # end_time = sleep_time["end"]
        # rf_status = request_data.get("rf_status")
        # power_switch = request_data.get("power_switch")
        #
        #
        #
        # # transmission_power的修改
        # # if transmission_power < 18 or transmission_power > 24:
        # #     print(f"修改失败，小区最大发射功率的范围应为18-24，当前为{transmission_power}")
        # # else:
        # #     action("set_MaxTxPower_info", transmission_power)
        #
        # print(f"修改失败，小区最大发射功率的范围应为18-24，当前为{transmission_power}")
        #
        # # 射频状态设置
        # action("set_RF_status", 1 if rf_status else 0)
        # # 供电开关设置
        # action("set_RRU_power", 1 if power_switch else 0)
        # sleep_time_str = "start_time + "-" + end_time"
        # action("set_EnergySave_time", sleep_time_str)
        # # return JsonResponse({"message": "real base station has been changed successfully"}, status=200)
        return JsonResponse({"message": "真实基站的数据已经修改"}, status=200)

    except Exception as e:
        print(f"当前的错误是{str(e)}")
        return JsonResponse({'error': str(e)}, status=500)


import asyncio
def demoapi1(request):
    return JsonResponse({"message": "立即返回响应"}, status=200)

async def demoapi2(request):
    async def long_running_task():
        cnt = 0
        while True:
            cnt += 1
            if cnt == 1000000000:
                break
    await asyncio.to_thread(long_running_task)
    return JsonResponse({"message": "10秒后成功返回响应"}, status=200)

# def current_parameter(request):
#     if request.method == 'POST':



def loginPart(request):
    data = json.loads(request.body)
    print(data)
    username_list = ["username"]
    password_list = ["password"]
    if (data["username"] in username_list) and (data["password"] in password_list):
        return JsonResponse({"result":"success"},status=200)
    # return JsonResponse({'status': 'error', 'message': 'Method not allowed'}, status=405)

# 用于直接传回预先设置的数据
def api_final_res_demo(request):
    request_data = json.loads(request.body)
    time_id = request_data.get("time")
    bs_num = cache.get("bs_num")
    res = get_cheat(time_id, bs_num)
    return JsonResponse(res)
    # return HttpResponse("可以进行返回")
#
# def api_bs_info(request):
#     # request_data = json.loads(request.body)
#     # time_id = request_data.get("time")
#     time_id = 0
#     bs_num = cache.get("bs_num")
#     res = get_cheat_bs(time_id, bs_num)
#     return JsonResponse(res)
#
# def api_user_info(request):
#     request_data = json.loads(request.body)
#     time_id = request_data.get("time")
#     bs_num = cache.get("bs_num")
#     res = get_cheat_user(time_id, bs_num)
#     return JsonResponse(res)